//
//  BTCityAndSceneScrollViewController.m
//  BaiduTravel
//
//  Created by Wu Chengwei on 12-9-6.
//
//

#import "BTCityAndSceneScrollViewController.h"
#import "UIImageView+WebCache.h"
#import "UIColor-Expanded.h"
#import "NCPictureViewerBar.h"
#import "NCSinglePictureViewer.h"
#import <QuartzCore/QuartzCore.h>
#import "TravelException.h"
#import "TTTAttributedLabel.h"
#import "NSAttributedString+LVAddition.h"
#import "NSString+NSString_Ex_.h"
#import "CommonDefines.h"
#import "UIImageView+CutToResize.h"
#import "RCMerchantPicturesDataModel.h"
#import "AppDelegate.h"
#import "NSArray+EX.h"

#define kHeaderViewTextBGImage                      @"image_sceneNatived_city_scrollView_BG.png"
#define kHeaderBackNormalImage              @"lv_scrollView_back_normal@2x.png"
#define kHeaderBackPressedImage             @"lv_scrollView_back_pressed@2x.png"
#define kHeaderSaveNormalImage              @"lv_scrollView_save_normal@2x.png"
#define kHeaderSavePressedImage             @"lv_scrollView_save_pressed@2x.png"
#define kStartActiveImageFile               @"image_start_active.png"
#define kStartInActiveImageFile             @"image_merchant_inactive.png"

#define KStartPoint                                 100
#define kBorderColor                                0xFF303030

#define kNaviBarSearchBtnCenter		        CGPointMake(290, 22)
#define kNaviBarDeleteBtnCenter		        CGPointMake(250, 22)
#define kNaviBarBackBtnCenter               CGPointMake(30,22)

#define UIScreenHeightEx                    (UIScreenHeight)


@interface BTCityAndSceneScrollViewController ()

@property(nonatomic, copy) NSString* deletePath;
@property(nonatomic, assign) int pageNumberOfFirstEntering;

@end

@implementation BTCityAndSceneScrollViewController
@synthesize pageController;
@synthesize scrollView = _scrollView;
@synthesize imageDataArray;
@synthesize containPictureInfo;
@synthesize currentPageNumber;
@synthesize imageViewArray;
@synthesize loadWeb;
@synthesize sid = _sid;
@synthesize isCity = _isCity;
@synthesize animationDelegate = _animationDelegate;
@synthesize shouldShowAnimation = _shouldShowAnimation;
@synthesize pageNumberOfFirstEntering = _pageNumberOfFirstEntering;
@synthesize hideExtraInfo = _hideExtraInfo;
@synthesize showHideInfoWhenScrollDidEnd = _showHideInfoWhenScrollDidEnd;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id)initWithRequestParam:(NSArray *)imageArr CurrentPageNumber:(int)pageNumber  IsContainPictureInfo:(BOOL)containInfo LoadFromWeb:(BOOL)loadFromWeb{
    self = [super init];
    if (self) {
        self.wantsFullScreenLayout = YES;
        imageDataArray = [[NSMutableArray alloc]init];
        self.imageDataArray = [NSMutableArray arrayWithArray:imageArr];
        self.containPictureInfo = containInfo;
        self.currentPageNumber = pageNumber;
        self.loadWeb = loadFromWeb;
        _viewControllers = [[NSMutableArray alloc]init];
        _saveFlagArray = [[NSMutableArray alloc]init];
        for (int i=0; i<[imageArr count]; i++) {
            [_viewControllers addObject:[NSNull null]];
            [_saveFlagArray addObject:[NSNumber numberWithBool:YES]];
        }

    }
    return self;
}

- (void)superViewLoadView
{
    [super loadView];
}

-(void) loadView{
    [super loadView];
    self.view.layer.contents = nil;
    self.wantsFullScreenLayout = YES;
    self.returnBtn.hidden = YES;
    self.navigationController.navigationBarHidden = YES;
    
    
    if (self.shouldShowAnimation) {
        self.navigationController.navigationBar.tintColor = [UIColor colorWithWhite:0 alpha:0];
        self.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    }else{
        self.navigationController.navigationBar.tintColor = [UIColor colorWithWhite:0 alpha:1];
        self.view.backgroundColor = [UIColor colorWithWhite:0 alpha:1];
    }
    _contentView = [[UIView alloc]initWithFrame:self.view.bounds];
    _contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    _contentView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:_contentView];
    
    if (!_ncPicViewerBar) {
        _ncPicViewerBar = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenHeight-44, 320, 44)];
        _ncPicViewerBar.backgroundColor = [UIColor colorWithHex:0x7f000000];
    }
    NSString *resourcePath = [[NSBundle mainBundle]resourcePath];
    if (!_backButton)
    {
        _backButton = [[NCNaviReturnButtonWithNoBG alloc] initRectBtnWithNormalStateString:nil withHighlightedStateString:nil];
        _backButton.backgroundColor = [UIColor clearColor];
        [_backButton setImage:[UIImage imageWithContentsOfFile:[resourcePath stringByAppendingPathComponent:kHeaderBackNormalImage]] forState:UIControlStateNormal];
        [_backButton setImage:[UIImage imageWithContentsOfFile:[resourcePath stringByAppendingPathComponent:kHeaderBackPressedImage]] forState:UIControlStateHighlighted];
        [_backButton addTarget:self action:@selector(backButtonClicked) forControlEvents:UIControlEventTouchUpInside];
        _backButton.hidden = YES;
        _backButton.center = kNaviBarBackBtnCenter;
    }
    if (!_picLocation) {
        _picLocation = [[UILabel alloc] initWithFrame:CGRectZero];
        _picLocation.center = CGPointMake(40, 22);
        _picLocation.bounds = CGRectMake(0, 0, 100, 40);
        [_picLocation setBackgroundColor:[UIColor clearColor]];
        [_picLocation setTextColor:[UIColor whiteColor]];
        _picLocation.textAlignment = UITextAlignmentCenter;
    }
    if (!_saveButton)
    {
        _saveButton = [[NCNaviReturnButtonWithNoBG alloc] initRectBtnWithNormalStateString:nil withHighlightedStateString:nil];
        [_saveButton setImage:[UIImage imageWithContentsOfFile:[resourcePath stringByAppendingPathComponent:kHeaderSaveNormalImage]] forState:UIControlStateNormal];
        [_saveButton setImage:[UIImage imageWithContentsOfFile:[resourcePath stringByAppendingPathComponent:kHeaderSavePressedImage]] forState:UIControlStateHighlighted];
        [_saveButton addTarget:self action:@selector(saveButtonClicked) forControlEvents:UIControlEventTouchUpInside];
        _saveButton.center = kNaviBarSearchBtnCenter;
        _saveButton.enabled = NO;
    }
    
    [_ncPicViewerBar addSubview:_backButton];
    [_ncPicViewerBar addSubview:_picLocation];
    [_ncPicViewerBar addSubview:_saveButton];
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, UIScreenHeightEx)];
    _scrollView.backgroundColor = [UIColor blackColor];
    [_contentView addSubview:_scrollView];
    //    [self.view addSubview:pageController];
    [_contentView addSubview:_ncPicViewerBar];
    if (self.containPictureInfo) {
        
        if (!textBGView)
        {
            textBGView = [[UIImageView alloc]initWithFrame:CGRectMake(0, UIScreenHeightEx-44-50, 320, 40)];
//            [textBGView setImage:[UIImage imageNamed:kHeaderViewTextBGImage]];
//            textBGView.layer.masksToBounds = YES;
//            textBGView.layer.cornerRadius = 6.0;
//            textBGView.layer.borderWidth = 1.0;
//            textBGView.layer.borderColor = [[UIColor colorWithHex:kBorderColor]CGColor];
            [_contentView addSubview:textBGView];
        }
        
        if (!textLabel)
        {
            CGRect labelRect = CGRectMake(17, 2, 200, 16);
            textLabel = [[UILabel alloc]initWithFrame:labelRect];
            textLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:16];
            textLabel.textColor = [UIColor colorWithHex:0xFFFFFFFF];
            textLabel.numberOfLines = 0;
            textLabel.backgroundColor = [UIColor clearColor];
            [textBGView addSubview:textLabel];
        }
        
        if (!_descLabel)
        {
            _descLabel = [[TTTAttributedLabel alloc]init];
            _descLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:16];
            _descLabel.textColor = [UIColor whiteColor];
            _descLabel.numberOfLines = 0;
            _descLabel.backgroundColor = [UIColor clearColor];
            [textBGView addSubview:_descLabel];
        }
        
        _dotLabel = [[UILabel alloc]initWithFrame:CGRectMake(17, 20, 286, 4)];
        _dotLabel.backgroundColor = [UIColor clearColor];
        _dotLabel.font = [UIFont fontWithName:kFontNameHelvetica size:4];
        _dotLabel.textColor = [UIColor whiteColor];
        
        [textBGView addSubview:_dotLabel];
        
        _timeLabel = [[UILabel alloc]initWithFrame:CGRectZero];
        _timeLabel.backgroundColor = [UIColor clearColor];
        _timeLabel.textColor = [UIColor colorWithHex:0xff7b7b7b];
        _timeLabel.font = [UIFont fontWithName:kFontNameHelvetica size:14];
        [textBGView addSubview:_timeLabel];
        
        _starView = [[UIView alloc]initWithFrame:CGRectMake(228, 4, 75, 14)];
        _starView.backgroundColor = [UIColor clearColor];
        
        _starArray = [[NSMutableArray alloc]init];
        UIImageView *startImageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 14, 14)];
        startImageView1.backgroundColor = [UIColor clearColor];
        [_startView addSubview:startImageView1];
        [_starArray addObject:startImageView1];
        [startImageView1 release];
        
        UIImageView *startImageView2 = [[UIImageView alloc]initWithFrame:CGRectMake(15, 0, 14, 14)];
        startImageView2.backgroundColor = [UIColor clearColor];
        [_startView addSubview:startImageView2];
        [_starArray addObject:startImageView2];
        [startImageView2 release];
        
        UIImageView *startImageView3 = [[UIImageView alloc]initWithFrame:CGRectMake(30, 0, 14, 14)];
        startImageView3.backgroundColor = [UIColor clearColor];
        [_startView addSubview:startImageView3];
        [_starArray addObject:startImageView3];
        [startImageView3 release];
        
        UIImageView *startImageView4 = [[UIImageView alloc]initWithFrame:CGRectMake(45, 0, 14, 14)];
        startImageView4.backgroundColor = [UIColor clearColor];
        [_startView addSubview:startImageView4];
        [_starArray addObject:startImageView4];
        [startImageView4 release];
        
        UIImageView *startImageView5 = [[UIImageView alloc]initWithFrame:CGRectMake(60, 0, 14, 14)];
        startImageView5.backgroundColor = [UIColor clearColor];
        [_startView addSubview:startImageView5];
        [_starArray addObject:startImageView5];
        [startImageView5 release];
    }
    
    int numberOfPages = [self.imageDataArray count];
    
    _scrollView.pagingEnabled = YES;
    _scrollView.contentSize = CGSizeMake(320*numberOfPages,UIScreenHeightEx);
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.minimumZoomScale = 1.0;
    _scrollView.maximumZoomScale = 5.0;
    _scrollView.delegate = self;
    self.pageNumberOfFirstEntering = self.currentPageNumber;
    if (self.containPictureInfo) {

        [self loadImageText:self.currentPageNumber];
        
    }
    
    
    _picLocation.text = [NSString stringWithFormat:@"%d/%d",self.currentPageNumber+1,numberOfPages];
    
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];

    [_scrollView addGestureRecognizer:singleTap];
    [singleTap release];
    
    
    [self loadImageAtIndex:currentPageNumber];
    [self loadImageAtIndex:currentPageNumber-1];
    [self loadImageAtIndex:currentPageNumber + 1];
    _scrollView.contentOffset = CGPointMake(320*self.currentPageNumber, 0);
    
    [_contentView bringSubviewToFront:textBGView];
    
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    //    [self loadImageAtIndex:0];
	// Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    _scrollView.delegate = nil;
    [_scrollView release];
    _scrollView = nil;
    [_ncPicViewerBar release];
    _ncPicViewerBar = nil;
    [_backButton release];
    _backButton = nil;
    [_picLocation release];
    _picLocation = nil;
    [textBGView release];
    textBGView = nil;
    [textLabel release];
    textLabel = nil;
    [_descLabel release];
    _descLabel = nil;
    [_saveButton release];
    _saveButton = nil;
    [_contentView release];
    _contentView = nil;
    [_fromImageView release];
    _fromImageView = nil;
    
    [_fromImage release];
    _fromImage = nil;
}

- (void)superViewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (self.shouldShowAnimation) {
        _contentView.hidden = YES;
        
        void (^animations)() = ^{
            _fromImageView.frame = _contentView.frame;
            _fromImageView.image = _fromImage;
            _fromImageView.alpha = 1;
            self.navigationController.navigationBar.tintColor = [UIColor colorWithWhite:0 alpha:1];
            self.view.backgroundColor = [UIColor colorWithWhite:0 alpha:1];
        };
        
        void (^completion)(BOOL) = ^(BOOL finished) {
            if (!finished) {
                animations();
            }
            if (_fromImageView) {
                [_fromImageView removeFromSuperview];
                [_fromImageView release],_fromImageView = nil;
            }
            [_fromImage release],_fromImage = nil;
            _contentView.hidden = NO;
        };
        
        if ([self shouldAnimatedWhenViewDidAppear]) {
            _fromImageView = [[UIImageView alloc] initWithFrame:_fromRect];
            _fromImageView.alpha = 0.2;
            _fromImageView.contentMode = UIViewContentModeScaleAspectFit;//UIViewContentModeCenter;
            _fromImageView.image = _fromImage;
            [self.view addSubview:_fromImageView];
            KFLog(@"from image view rect %@, image size %@",NSStringFromCGRect(_fromImageView.frame),NSStringFromCGSize(_fromImageView.image.size));
            
            [UIView animateWithDuration:.5 animations:animations completion:completion];
        } else {
            animations();
            completion(YES);
        }
    }
}

- (void)superViewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

-(void) viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

#pragma mark TapDetectingScrollViewDelegate methods

- (void)handleSingleTap:(UIGestureRecognizer *)gestureRecognizer
{
    
    @synchronized(self) {
        //退出
        if (self.view.userInteractionEnabled == NO) {
            //防止系统卡死，导致事件突然接收到多个。然后某些对象被释放，crash了
            return;
        }
        self.view.userInteractionEnabled = NO;
    }
    
    [self backButtonClicked];
    return;
    
    // single tap open or close bar
    if (_ncPicViewerBar.hidden == YES) {
        // hide the picture viewer bar
        
        
        BOOL animated = YES;
        
        if (animated)
        {
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.3];
        }

        [[UIApplication sharedApplication] setStatusBarHidden:NO];
        textBGView.alpha = 1.0;
        _ncPicViewerBar.hidden = NO;
        if (animated)
        {
            [UIView commitAnimations];
        }
    }
    else
    {
        //show the picture viewer bar
        
        BOOL animated = YES;
        
        if (animated)
        {
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.3];
        }
   
        textBGView.alpha = 0.0;

        _ncPicViewerBar.hidden = YES;
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
        
        if (animated)
        {
            [UIView commitAnimations];
        }
    }
}



//加载图片信息
-(void) loadImageText:(NSInteger) currentPage{
    if (currentPage < 0) {
        return;
    }else if (currentPage >= [imageDataArray count]) {
        return;
    }
    RCMerchantPictureItem *absInfo = [self.imageDataArray objectAtIndex:currentPage withDefaultValue:nil];
    NSString *textString = absInfo.photoTitle;
    NSString *descString = absInfo.userName;
    NSString *timeString = nil;
    if (![NSString stringIsNullOrEmpty:absInfo.photoDateTime]) {
        timeString = [NSString stringWithFormat:@"上传于%@",absInfo.photoDateTime];
    }
    if ((textString !=nil && ![NSString stringIsNullOrEmpty:textString]) || (descString !=nil && ![NSString stringIsNullOrEmpty:descString]) ||
        ![NSString stringIsNullOrEmpty:timeString]) {
        _dotLabel.hidden = YES;
        textBGView.hidden = NO;
        textLabel.hidden = YES;
        _descLabel.hidden = YES;
        _timeLabel.hidden = YES;
        
        BOOL hasTitle = NO;
        if ((textString !=nil && ![NSString stringIsNullOrEmpty:textString])) {
            textLabel.text = textString;
            textLabel.hidden = NO;
            hasTitle = YES;
        }
        
        _starView.hidden = YES;
        if (absInfo.photoScore > 0) {
            _starView.hidden = NO;
            UIImage *activeImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:kStartActiveImageFile ofType:nil]];
            UIImage *inactiveImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:kStartInActiveImageFile ofType:nil]];
            for (int i = 0; i < [_starArray count]; i++) {
                UIImageView *starView = [_starArray safeObjectAtIndex:i];
                if (absInfo.photoScore >i) {
                    [starView setImage:activeImage];
                }else{
                    [starView setImage:inactiveImage];
                }
            }
        }
        
        CGFloat width = 17;
        if ((descString !=nil && ![NSString stringIsNullOrEmpty:descString])) {
            _descLabel.text = descString;
            if (hasTitle) {
                _dotLabel.hidden = NO;
            }
            
            _descLabel.hidden = NO;
            
            CGSize descSize = [_descLabel.text sizeWithFont:_descLabel.font constrainedToSize:CGSizeMake(300, 80)];
            _descLabel.frame = CGRectMake(17, 26, descSize.width, 14);
            width +=descSize.width;
        }
        
        if (![NSString stringIsNullOrEmpty:timeString]) {
            _timeLabel.hidden = NO;
            _timeLabel.text = timeString;
            _timeLabel.frame = CGRectMake(width+2, 26, 303-width-2, 14);
        }
        
    }else{
        textBGView.hidden = YES;
        textLabel.hidden = YES;
        _descLabel.hidden = YES;
        _timeLabel.hidden = YES;
        _dotLabel.hidden = YES;
        _starView.hidden = YES;
    }
}


-(void) loadImageAtIndex:(NSInteger) currentPage  //加载图片
{
    if (currentPage < 0) {
        return;
    }else if (currentPage >= [imageDataArray count]) {
        return;
    }
    UIView *loadingView = (UIView *)[_scrollView viewWithTag:currentPage+300];
    if (loadingView == nil) {
        NSString *urlString = nil;
        if (loadWeb) {
            //containPictureInfo 为了兼容之后imagedataarray中只是图片的URL
            if (self.containPictureInfo) {
                RCMerchantPictureItem *absInfo = [self.imageDataArray objectAtIndex:currentPage withDefaultValue:nil];
                urlString = absInfo.photoBigPicUrl;
            }else{
                urlString = [self.imageDataArray objectAtIndex:currentPage withDefaultValue:nil];
            }
        }else{
            if (self.containPictureInfo) {
                RCMerchantPictureItem *absInfo = [self.imageDataArray objectAtIndex:currentPage withDefaultValue:nil];
                urlString = absInfo.photoBigPicUrl;
            }else{
                urlString = [self.imageDataArray objectAtIndex:currentPage withDefaultValue:nil];
            }
        }
    
        
        NCSinglePictureViewerFullScreen *singlePicController = [[NCSinglePictureViewerFullScreen alloc]initWithUrl:urlString AndPicID:@"test" Title:@"" Location:@""];
        //if ( self.currentPageNumber == self.pageNumberOfFirstEntering )
        //    singlePicController.waitingImage = _fromImage;
        loadingView = singlePicController.view;
        loadingView.tag = currentPage +300;
        loadingView.bounds = CGRectMake(0, 0, 320, UIScreenHeightEx);
        loadingView.center = CGPointMake(320*currentPage+160, UIScreenHeightEx/2);
        singlePicController.touchDelegate = (id<NCSinglePictureViewerDelegate>)self;
        [_scrollView addSubview:loadingView];
        [_viewControllers replaceObjectAtIndex:currentPage withObject:singlePicController];
        if (currentPage == currentPageNumber) {
            NSNumber *number = [_saveFlagArray objectAtIndex:currentPage withDefaultValue:nil];
            _saveButton.enabled = number.boolValue;
            //            _saveButton.enabled = singlePicController.saveStateEnable;
        }
        [singlePicController release];
    }
    
    
}

- (void)loadImageViewAndText
{
    int page = self.currentPageNumber;
    int numberOfPages = [self.imageDataArray count];
    
    _picLocation.text = [NSString stringWithFormat:@"%d/%d",page+1,numberOfPages];
    
    [self loadImageAtIndex:page -1];
    [self loadImageAtIndex:page];
    [self loadImageAtIndex:page +1];
    
    if (self.containPictureInfo) {
        [self loadImageText:page];
    }
    
    NCSinglePictureViewerFullScreen *picViewController = [_viewControllers objectAtIndex:page];
    if (picViewController != (NCSinglePictureViewerFullScreen *)[NSNull null]) {
        NSNumber *number= [_saveFlagArray objectAtIndex:page withDefaultValue:nil];
        _saveButton.enabled = number.boolValue;
        //        _saveButton.enabled = picViewController.saveStateEnable;
    }
    
    for (int i=0; i < [_viewControllers count]; i++) {
        BOOL notToadingThree = (i != self.currentPageNumber  &&  i!= self.currentPageNumber -1 && i!=self.currentPageNumber+1 );
        if (notToadingThree) {
            NCSinglePictureViewerFullScreen *pic_obj = (NCSinglePictureViewerFullScreen*) [_viewControllers objectAtIndex:i];
            if (pic_obj != (NCSinglePictureViewerFullScreen*)[NSNull null]) {
                [pic_obj.view removeFromSuperview];
                [pic_obj viewDidUnload];
            }
            [_viewControllers replaceObjectAtIndex:i withObject:[NSNull null]];
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self hidePicViewerBarWhenScrollBegan];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollViewT willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
    {
        CGFloat pageWidth = scrollViewT.frame.size.width;
        int page = ((scrollViewT.contentOffset.x - pageWidth/2)/pageWidth)+1;
        
        if (page <0 || page >= [imageDataArray count] || page == self.currentPageNumber)
        {
            return;
        }
        
        self.currentPageNumber = page;
        [self scrollViewDidEndDecelerating:scrollViewT];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    KFLog(@"Decelerating........");
    [self loadImageViewAndText];
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(showPicViewerBarWhenScrollEnded) object:nil];
    [self performSelector:@selector(showPicViewerBarWhenScrollEnded) withObject:nil afterDelay:1.0];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollViewT
{
    CGFloat pageWidth = scrollViewT.frame.size.width;
    int page = ((scrollViewT.contentOffset.x - pageWidth/2)/pageWidth)+1;
    
    KFLog(@"Page = %d ----%d",page,scrollViewT.decelerating);
    
    if (page <0 || page >= [imageDataArray count] || page == self.currentPageNumber) {
        return;
    }
    
    
    self.currentPageNumber = page;
    
    if (scrollViewT.decelerating)
    {
        [self loadImageViewAndText];
    }
}

-(void) showPicViewerBarWhenScrollEnded
{
    if ( NO == _showHideInfoWhenScrollDidEnd )
        return;
    [UIView animateWithDuration:0.3 animations:^(void){
        textBGView.alpha = 1.0;
        _ncPicViewerBar.alpha = 1.0;
    }];
}

-(void) hidePicViewerBarWhenScrollBegan
{
    if ( NO == _showHideInfoWhenScrollDidEnd )
        return;
    
    [UIView animateWithDuration:0.3 animations:^(void){
        textBGView.alpha = 0.0;
        _ncPicViewerBar.alpha = 0.0;
    }];
}

- (void) imageNoticeToChangeDownloadButton
{
    NCSinglePictureViewerFullScreen *picViewController = [_viewControllers objectAtIndex:self.currentPageNumber withDefaultValue:nil];
    if (picViewController != (NCSinglePictureViewerFullScreen*)[NSNull null] ) {
        NSNumber *number= [_saveFlagArray objectAtIndex:self.currentPageNumber withDefaultValue:nil];
        _saveButton.enabled = number.boolValue;
        //        _saveButton.enabled = picViewController.saveStateEnable;
    }
    
}

#pragma mark - navigationbar button action

- (void)saveButtonClicked
{
    _saveButton.enabled = NO;
    
    if (self.currentPageNumber < [self.imageDataArray count] && self.currentPageNumber >= 0) {
        NCSinglePictureViewerFullScreen *picContorller = [_viewControllers objectAtIndex:self.currentPageNumber withDefaultValue:nil];
        if (picContorller != nil && picContorller != (NCSinglePictureViewerFullScreen*)[NSNull null]) {
            if (!picContorller.imageView.image)
            {
                [RCAppDelegate alertWithCustomizeString:@"哎呀，保存失败了！"];
                _saveButton.enabled = YES;
                return;
            }
            [picContorller saveButtonClicked];
            picContorller.saveStateEnable = NO;
            [_saveFlagArray removeObjectAtIndex:self.currentPageNumber];
            [_saveFlagArray insertObject:[NSNumber numberWithBool:NO] atIndex:self.currentPageNumber];
        }
    }
    
}

-(void)backButtonClicked{
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(showPicViewerBarWhenScrollEnded) object:nil];
    if (self.shouldShowAnimation) {
        CGRect rect = _fromRect;
        
        
        void (^animations)() = ^{
            _fromImageView.frame = rect;
            _fromImageView.alpha = 0.2;
            
            self.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0];;
        };
        
        void (^completion)(BOOL) = ^(BOOL finished) {
            if (!finished) {
                animations();
            }
            if (_fromImageView) {
                [_fromImageView removeFromSuperview];
                [_fromImageView release],_fromImageView = nil;
            }
            [self dismissViewControllerAnimatedWithCompatibility:NO];
        };
        
        
        
        if ([self shouldAnimatedWhenViewDidDisappear]) {
            _contentView.hidden = YES;
            _fromImageView = [[UIImageView alloc] initWithFrame:_contentView.frame];
            _fromImageView.contentMode = UIViewContentModeScaleAspectFit;
            
            if (self.currentPageNumber < [self.imageDataArray count] && self.currentPageNumber >= 0) {
                NCSinglePictureViewerFullScreen *picContorller = [_viewControllers objectAtIndex:self.currentPageNumber withDefaultValue:nil];
                if (picContorller != nil && picContorller != (NCSinglePictureViewerFullScreen*)[NSNull null]) {
                    if ( picContorller.imageView.image != nil )
                        _fromImageView.image = picContorller.imageView.image;
                }
            }
            
            [self.view addSubview:_fromImageView];
            
            [UIView animateWithDuration:.5 animations:animations completion:completion];
        } else {
            animations();
            completion(YES);
        }
    }else{
        [self dismissViewControllerAnimatedWithCompatibility:YES];
    }
    
}


-(void)dealloc{
    self.deletePath = nil;
    self.coverUrl = nil;
    [_scrollView release];
    [imageDataArray release];
    [imageViewArray release];
    if (textBGView) [textBGView release];
    if (textLabel) [textLabel release];
    if (_descLabel)[_descLabel release];
    [_startView release], _startView = nil;
    [_timeLabel release], _timeLabel = nil;
    [_starArray release], _starArray = nil;
    [_dotLabel release], _dotLabel = nil;
    [_viewControllers release];
    [_saveFlagArray release];
    [_saveButton release];
    [_backButton release];
    [_picLocation release];
    [_ncPicViewerBar release];
    [_contentView release];
    [_fromImage release];
    [_fromImageView release];
    self.sid = nil;
    self.pageController = nil;
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - 动画
-(void) setFromImage:(UIImage *) image fromWindowRect:(CGRect) rect {
    
    if ( _fromImage != image ) {
        [_fromImage release];
        _fromImage = [image retain];
    }
    //if (rect.size.width > 200) {
    //    rect.size.width = 200.0f;
    //    rect.origin.x = 60.0f;
    //}
    _fromRect = rect;
//    if (![UIApplication sharedApplication].statusBarHidden) {
//        _fromRect = CGRectOffset(rect, 0, 20);
//    } else {
//        _fromRect = rect;
//    }
    
    
}

-(BOOL) shouldAnimatedWhenViewDidAppear {
    if([_animationDelegate respondsToSelector:@selector(shouldAnimatedWhenViewDidAppearForPhotoPreviewViewController:)]) {
        return [_animationDelegate shouldAnimatedWhenViewDidAppearForPhotoPreviewViewController:self];
    }
    return NO;
}

-(BOOL) shouldAnimatedWhenViewDidDisappear {
    if([_animationDelegate respondsToSelector:@selector(shouldAnimatedWhenViewDidDisappearForPhotoPreviewViewController:)]) {
        return [_animationDelegate shouldAnimatedWhenViewDidDisappearForPhotoPreviewViewController:self];
    }
    return NO;
}


#pragma mark - NCSinglePictureViewer delegate
-(void) pictureZoomBegan
{
    [self scrollViewWillBeginDragging:_scrollView];
}

-(void) pictureZoomEnded
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(showPicViewerBarWhenScrollEnded) object:nil];
    [self performSelector:@selector(showPicViewerBarWhenScrollEnded) withObject:nil afterDelay:1.0];
}


@end


